<template>
  <div class="login-container">
    <div class="input-cell">
      <input v-model="username" class="login-input" placeholder="请输入手机号" type="number" />
      <div class="login-icon">
        <img src="@/assets/登录-assets/telephone.png" alt />
      </div>
    </div>
    <div class="input-cell">
      <input v-model="password" class="login-input" placeholder="请输入密码" type="password" />
      <div class="login-icon">
        <img src="@/assets/登录-assets/password.png" alt />
      </div>
    </div>
    <div class="small-btn-container">
      <router-link class="small-btn" to="/psw-reset" :style="{color: mainColor}">忘记密码？</router-link>
      <div class="small-btn" @click="toRegister" :style="{color: mainColor}">注册</div>
    </div>
    <button @click="login" class="main-btn" :style="{background: mainColor}">登 录</button>
    <div class="login-type">
      <div class="title">
        <div class="line"></div>
        <div class="type-title">快捷登录</div>
        <div class="line"></div>
      </div>
      <div class="type">
        <div>
          <router-link
            class="type-icon mobile"
            :to="{
              path: '/mobile-login'
            }"
          ></router-link>
          <div class="type-text">快捷登录</div>
        </div>
        <div @click="wechatLogin">
          <router-link class="type-icon wechat" to="/login"></router-link>
          <div class="type-text">微信登录</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import "./login-style.less";
import { mapActions, mapState, mapMutations } from "vuex";
import { getUserInfo } from "@/api/profile";
import { wechatLogin } from "@/api/login";
import wx from "weixin-js-sdk";
export default {
  data() {
    return {
      username: null,
      password: null,
      code: "",
      invite_code: ""
    };
  },
  computed: {
    ...mapState({
      menu: state => state.app.menu,
      mainColor: state => state.app.mainColor,
      subColor: state => state.app.subColor,
      index_advertising: state => state.app.index_advertising
    })
  },
  methods: {
    ...mapMutations(["loginSetInfo"]),
    ...mapActions(["handleLogin", "setUserInfo"]),
    toRegister() {
      console.log(this.$route.query.invite_code, "///");
      if (this.$route.query.invite_code) {
        this.$router.push({
          path: "/register",
          query: { invite_code: this.$route.query.invite_code }
        });
        return;
      }
      this.$router.push("/register");
    },
    login() {
      let username = this.username;
      let password = this.password;

      this.handleLogin({
        username,
        password,
        isCaptcha: false,
        invite_code: this.$route.query.invite_code
      }).then(res => {
        console.log(res, "login");
        if (res) {
          getUserInfo().then(res => {
            if (res.status === 200) {
              this.setUserInfo(res.data.data);
            }
          });
          this.$dialog.toast({
            mes: "登录成功！",
            timeout: 1500,
            callback: () => {
              this.routeHandle();
            }
          });
        } else {
        }
        // if (res.data.code === 208) {
        //   this.$dialog.toast({
        //     mes: res.data.message,
        //     timeout: 1500
        //   });
        // }
      });
    },
    symbolTrans(str) {
      str = str.replace(/\%/g, "%25");
      str = str.replace(/\+/g, "%2B");
      // str = str.replace(/ /g, "%20");
      str = str.replace(/\//g, "%2F");
      str = str.replace(/\?/g, "%3F");
      str = str.replace(/\#/g, "%23");
      str = str.replace(/\=/g, "%3D");
      return str;
    },
    routeHandle() {
      if (
        localStorage.getItem("ct_invite_code") &&
        localStorage.getItem("ct_good_id")
      ) {
        this.$router.replace(this.menu[0].link);
        this.$router.push({
          path: "/item-detail/" + localStorage.getItem("ct_good_id"),
          query: {
            invite_code: localStorage.getItem("ct_invite_code")
          }
        });
      } else {
        this.$router.replace(this.menu[0].link);
      }
      localStorage.removeItem("ct_invite_code");
      localStorage.removeItem("ct_good_id");
    },
    wechatLoginHandle() {
      // alert(this.code)
      wechatLogin({ code: this.code }).then(res => {
        if (res.status === 200) {
          // alert(res.data.data.status)
          if (res.data.data.status === 1) {
            this.loginSetInfo(res.data.data);
            getUserInfo().then(res => {
              if (res.status === 200) {
                this.setUserInfo(res.data.data);
              }
            });
            this.$dialog.toast({
              mes: "登录成功！",
              timeout: 1500,
              callback: () => {
                this.routeHandle();
              }
            });
          } else {
            this.$dialog.toast({
              mes: "请绑定手机号",
              timeout: 1500,
              callback: () => {
                this.$router.push({
                  path: "/mobile-login",
                  query: { secret: res.data.data.secret }
                });
              }
            });
          }
        }
      });
    },
    getPureHref() {
      return (
        window.location.href.split("?code=")[0] +
        window.location.href.split("wechat")[1]
      );
    },
    wechatLogin() {
      if (window.location.href.indexOf("?code=") !== -1) {
        window.location.href = this.getPureHref();
      } else {
        window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${
          this.$config.appid
        }&redirect_uri=${this.symbolTrans(
          window.location.href
        )}&response_type=code&scope=snsapi_userinfo&state=wechat&#wechat_redirect`;
        // wx.miniProgram.navigateTo({
        //   url: "/pages/login/login"
        // });
      }
    }
  },

  created() {
    if (this.$route.query.invite_code) {
      localStorage.setItem("ct_invite_code", this.$route.query.invite_code);
      this.invite_code = this.$route.query.invite_code;
    }
    if (this.$route.query.good_id) {
      localStorage.setItem("ct_good_id", this.$route.query.good_id);
    }
    let href = window.location.href;
    if (href.includes("/?code=") || href.includes("/?&code=")) {
      let code = href.split("code=")[1].split("&state=")[0];
      let baseUrl = href.includes("/?code=")
        ? href.split("?code=")[0]
        : href.split("?&code=")[0];
      let hash = href.split("#/")[1];
      window.location.href = baseUrl + "#/" + hash + "?code=" + code;
    } else if (href.includes("/?from=")) {
      let baseUrl = href.split("?from=")[0];
      let hash = href.split("#/")[1];
      window.location.href = baseUrl + "#/" + hash;
    }
    if (this.$route.query.code) {
      this.code = this.$route.query.code;
      this.wechatLoginHandle();
    }
  }
};
</script>

<style lang="less" scoped></style>
